package br.com.locasis.conversores;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import br.com.locasis.utilitarios.UtilString;

@org.jboss.seam.annotations.faces.Converter(id="conversorCnpj")
public class ConversorCnpj implements Converter {

    public Object getAsObject(FacesContext context, UIComponent component, String valorCampo){
	   Object cnpj = null;
	   if(valorCampo != null) {
           if(!UtilString.isStringVazia(valorCampo)){
               cnpj = desmascara(valorCampo);
           }
	   }
	   return cnpj;
    }

    public String getAsString(FacesContext context, UIComponent component, Object objCampo){
       String cnpj = null;
       if(objCampo != null) {
           if(!UtilString.isStringVazia(objCampo.toString())){
               cnpj = mascara(objCampo);
           }
       }
       return cnpj;
    }
    
    public static Object desmascara(String cpf) {
       cpf = UtilString.removeAll('.', cpf);
       cpf = UtilString.removeAll('-', cpf);
       cpf = UtilString.removeAll('/', cpf);
       return cpf;
    }

    public static String mascara(Object cnpj) {
	   StringBuffer zeros = new StringBuffer();
	   zeros.append("");
	   if(cnpj.toString().length() < 14){
           int tamanho = cnpj.toString().length();
           if(tamanho > 1){
	           int qtdeZeros = 11 - tamanho;                                  
	           for(int i = 0; i < qtdeZeros; i++){
	               zeros.append("0");
	           }
           }else{
        	   return cnpj.toString();
           }
	   }
	   StringBuffer stringBuffer = new StringBuffer(zeros.toString().concat(cnpj.toString()));
	   stringBuffer.insert(2, ".");
	   stringBuffer.insert(6, ".");
	   stringBuffer.insert(10, "/");
	   stringBuffer.insert(15, "-");
	   return stringBuffer.toString();
    }

}
